package com.tcwlkj.uuService.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.RelativeLayout;

import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.tcwlkj.uuService.MyApp;
import com.tcwlkj.uuService.NetWork.HttpCallBack;
import com.tcwlkj.uuService.NetWork.RetrofitUtils;
import com.tcwlkj.uuService.R;
import com.tcwlkj.uuService.adapter.ChatAdapter;
import com.tcwlkj.uuService.enums.CheckStatus;
import com.tcwlkj.uuService.model.CommonResponse;
import com.tcwlkj.uuService.model.LastFeedModle;
import com.tcwlkj.uuService.model.MainMessage;
import com.tcwlkj.uuService.model.PutQuestion;
import com.tcwlkj.uuService.utils.EventCenter;
import com.tcwlkj.uuService.utils.MyRefresh;
import com.tcwlkj.uuService.utils.PreferencesUtils;
import com.tcwlkj.uuService.utils.ToastUtil;
import com.tcwlkj.uuService.widget.chatview.ChatBottomView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/9/30 0030.
 * 在线客服
 */

public class CustomerServiceActivity extends BaseActivity implements ChatBottomView.Callback ,View.OnLayoutChangeListener{
    @Bind(R.id.rl_layout)
    RelativeLayout rl_layout;
    @Bind(R.id.chat_bottom_container)
    ChatBottomView chatBottomView;
    @Bind(R.id.refreshLayout)
    TwinklingRefreshLayout refreshLayout;
    @Bind(R.id.chat_recycle)
    RecyclerView chat_recycle;

    private ArrayList<LastFeedModle.DataBean> mChatDetail;
    private ChatAdapter adapter;
    String userID;
    int pindex=1;
    int psize=20;
    //屏幕高度
    private int screenHeight = 0;
    //软件盘弹起后所占高度阀值
    private int keyHeight = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer_service);
        ButterKnife.bind(this);
        changeTitle("在线客服");

        initview();
        getLastFeed();
        //获取屏幕高度
        screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
        //阀值设置为屏幕高度的1/3
        keyHeight = screenHeight/3;
    }

    private void initview() {
        chatBottomView.setCallback(this);
        MyRefresh.getInstance().getoneMusic(refreshLayout,false);
        mChatDetail=new ArrayList<>();
        adapter=new ChatAdapter(mChatDetail);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        chat_recycle.setLayoutManager(layoutManager);
        chat_recycle.setAdapter(adapter);
        chat_recycle.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                InputMethodManager imm =  (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                if(imm != null){
                    imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(),
                            0);
                }
                return false;
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        rl_layout.addOnLayoutChangeListener(this);
        refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        pindex++;
                        getLastFeed();
                        refreshLayout.finishRefreshing();
                    }
                },1000);
            }
        });
    }

    //发送
    @Override
    public void onSendMessage(CharSequence value, int type) {
        putquest();//发送内容
    }
    //弹出拍照
    @Override
    public void onMoreClick() {

    }
    //常见问题点击事件
    @Override
    public void onLeftButtonClick() {
        startActivityForResult(new Intent(this,CommonProblemActivity.class),1);
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        if(oldBottom != 0 && bottom != 0 &&(oldBottom - bottom > keyHeight)){
            chat_recycle.scrollToPosition(adapter.getItemCount()-1);
            adapter.notifyDataSetChanged();

        }else if(oldBottom != 0 && bottom != 0 &&(bottom - oldBottom > keyHeight)){

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==99){
            chatBottomView.setInputContentText(data.getStringExtra("TextCommon"));
        }
    }

    @Override
    protected boolean isBindEventBusHere() {
        return true;
    }

    @Override
    protected void onEventComing(EventCenter eventCenter) {
        super.onEventComing(eventCenter);
        if(eventCenter.getEventCode()==CheckStatus.Customer.getKey()){
            Bitmap bitmap=null;
            mChatDetail.add(new LastFeedModle.DataBean(0,eventCenter.getData().toString(),bitmap,stampToDate(System.currentTimeMillis()+"")));
            chat_recycle.scrollToPosition(adapter.getItemCount()-1);
            adapter.notifyDataSetChanged();
        }
    }

    public void putquest(){
        String content=chatBottomView.getInputContentText().toString();
        Call<CommonResponse> httpResultCall=RetrofitUtils.getRequest(this,false).putquest(PreferencesUtils.getString(MyApp.getContext(),"userID"),0,content,0,0,2);
        httpResultCall.enqueue(new HttpCallBack<CommonResponse>() {
            @Override
            public void onSuccess(Object t) {
                Bitmap bitmap=null;
                mChatDetail.add(new LastFeedModle.DataBean(1,content,bitmap,stampToDate(System.currentTimeMillis()+"")));
                chatBottomView.clearSendText();
                chat_recycle.scrollToPosition(adapter.getItemCount()-1);
            }
            @Override
            public void onFail(int code, String message) {
                if(code == 40104){
                    //putquest();
                }else {
                    ToastUtil.getInstance().show(message);
                }
            }
        });
    }
    public void getLastFeed() {
        userID= PreferencesUtils.getString(MyApp.getContext(),"userID");
        Call<CommonResponse<LastFeedModle>> httpResultCall=RetrofitUtils.getRequest(this,false).getLastFeed(PreferencesUtils.getString(MyApp.getContext(),"userID"),pindex,psize);
        httpResultCall.enqueue(new HttpCallBack<CommonResponse<LastFeedModle>>() {
            @Override
            public void onSuccess(Object t) {
                CommonResponse<LastFeedModle> commonResponse= (CommonResponse<LastFeedModle>) t;
                if(commonResponse.getData().getRows().size()==0){
                    ToastUtil.getInstance().show("没有更多数据");
                }
                if(pindex==1){
                    mChatDetail.clear();
                    mChatDetail.addAll(commonResponse.getData().getRows());
                    Collections.reverse(mChatDetail);
                    chat_recycle.scrollToPosition(adapter.getItemCount()-1);
                }else {
                    Collections.reverse(commonResponse.getData().getRows());
                    if(commonResponse.getData().getRows().size()>6){
                        chat_recycle.scrollToPosition(commonResponse.getData().getRows().size()+6);
                    }else {
                        chat_recycle.scrollToPosition(commonResponse.getData().getRows().size()+commonResponse.getData().getRows().size()+1);
                    }
                    mChatDetail.addAll(0,commonResponse.getData().getRows());
                }
                adapter.updateData(mChatDetail);
            }
            @Override
            public void onFail(int code, String message) {
                if(code == 40104){
                    getLastFeed();
                }else {
                    ToastUtil.getInstance().show(message);
                }
            }
        });

    }
    public static String stampToDate(String s){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }
}
